import SwiftUI
import PhotosUI
//import MobileCoreServices

@available(iOS 14, *)

public struct DogPHLibraryPicker: UIViewControllerRepresentable {
    
    @ Environment(\.presentationMode) private var presentation
    
    fileprivate let configure: PHPickerConfiguration
    @Binding fileprivate  var pickerResult: [PHPickerResult]
    
    public init(configure: PHPickerConfiguration, pickerResult: Binding<[PHPickerResult]>) {
        
        self.configure = configure
        self._pickerResult = pickerResult
    }
    
    
    public func makeUIViewController(context: Context) -> some PHPickerViewController {
        let controller = PHPickerViewController(configuration: configure)
        
        
        controller.delegate = context.coordinator
        return controller
    }
    
    public func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        
    }
    
    public func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    public class Coordinator: PHPickerViewControllerDelegate {
        
        private let parent: DogPHLibraryPicker
        
        init(_ parent: DogPHLibraryPicker) {
            
            self.parent = parent
        }
        
        public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            
            parent.pickerResult += results
            
            parent.presentation.wrappedValue.dismiss()
        }
    }
}

extension PHPickerResult {
    
    public func toImage() async -> (UIImage?, Error?) {
        
        return await withUnsafeContinuation({ c in
            
            itemProvider.loadObject(ofClass: UIImage.self) { image, error in
                
                c.resume(returning: (image as? UIImage, error))
            }
        })
    }
    

    
    public func toImage(completionHandler: @escaping (_ image: UIImage?, _ error: Error?) -> Void) {
                
        itemProvider.loadObject(ofClass: UIImage.self) { image, error in
            
            guard let image = image as? UIImage else {
                
                completionHandler(nil,error)
                return
            }
            
            completionHandler(image, nil)
        }
    }
    
    public func getFileName() async -> (String?, Error?) {
        
        let result = await getFileUrl()
        guard let url = result.0 else {
            
            return (nil, result.1)
        }
        
        return (url.lastPathComponent, nil)
    }
    
    public func getFileName(completionHandler: @escaping (String?, Error?) -> Void) {
    
        getFileUrl { url, error in
            guard let url = url else {
               completionHandler(nil,error)
               return
           }

           completionHandler(url.lastPathComponent, nil)
        }
    }
    
    public func getFileUrl() async -> (URL?, Error?) {
        
        return await withUnsafeContinuation { c in
            
            itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier) { url, error in
                
                return c.resume(returning: (url, error))
            }
        }
    }
    
    public func getFileUrl(completionHandler: @escaping (URL?, Error?) -> Void) {
        itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier, completionHandler: completionHandler)
    }
    
    public func getFileType() async -> (String?, Error?) {
        
        let result = await getFileUrl()
        guard let url = result.0 else {
            return (nil, result.1)
        }
        
        return (url.pathExtension, nil)
    }
    
    public func getFileType(completionHandler: @escaping (String?, Error?) -> Void) {
        
        getFileUrl { url, error in
            
            guard let url = url else {
                completionHandler(nil, error)
                return
            }
            
            completionHandler(url.pathExtension, nil)
        }
    }
}


